package com.star.common.orm.typehandlers;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 类型转换：Varchar <-> Double[]，使用英文逗号,分割
 *
 * @author zhouhengzhe
 */
@Slf4j
public class DoublesTypeHandler extends BaseTypeHandler<Double[]> {
    public DoublesTypeHandler() {
        log.debug("Loading DoublesTypeHandler, type: Double[]");
    }

    public void setNonNullParameter(PreparedStatement ps, int i, Double[] doubles, JdbcType jdbcType) throws SQLException {
        if (doubles == null || doubles.length == 0) return;
        StringBuilder sb = new StringBuilder();
        for (Double d : doubles) {
            sb.append(d).append(",");
        }
        sb.append("<END>");
        ps.setString(i, sb.toString().replace(",<END>", ""));
    }

    public Double[] getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String strings = rs.getString(columnName);
        if (CharSequenceUtil.isBlank(strings)) return new Double[0];
        String[] split = strings.split(",");
        List<Double> doubles = new ArrayList<>();
        for (String s : split) {
            doubles.add(Double.valueOf(s));
        }
        return doubles.toArray(new Double[]{});
    }

    public Double[] getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String strings = rs.getString(columnIndex);
        if (CharSequenceUtil.isBlank(strings)) return new Double[0];
        String[] split = strings.split(",");
        List<Double> doubles = new ArrayList<>();
        for (String s : split) {
            doubles.add(Double.valueOf(s));
        }
        return doubles.toArray(new Double[]{});
    }

    public Double[] getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String strings = cs.getString(columnIndex);
        if (CharSequenceUtil.isBlank(strings)) return new Double[0];
        String[] split = strings.split(",");
        List<Double> doubles = new ArrayList<>();
        for (String s : split) {
            doubles.add(Double.valueOf(s));
        }
        return doubles.toArray(new Double[]{});
    }

}
